package com.zhouxl.program.multi.seckill;

/**
 * 秒杀活动的lua脚本
 * @author zhouxl
 * @DATE 2021/7/14
 * @descriptoin
 */
public class SeckillLua {

    /** 活动并未开始 */
    public final static String SECKILL_NO_START = "2";
    /** 秒杀成功 */
    public final static String SECKILL_SUCCESS = "1";
    /** 秒杀异常 */
    public final static String SECKILL_EXCEPTION = "0";

    /**
     * 获取秒杀脚本
     * @return
     */
    public static String getSeckillScripts(){
        return "local userId = KEYS[1];\n" +
                "local prodId = KEYS[2];\n" +
                "local qtKey = \"sk:\"..prodId..\":prod\";\n" +
                "local usersKey = \"sk:\"..prodId..\":user\";\n" +
                "local userExists = redis.call(\"sismember\",usersKey,userId);\n" +
                "if tonumber(userExists) == 1 then\n" +
                "    return 2;\n" +
                "end\n" +
                "\n" +
                "local num = redis.call(\"get\",qtKey);\n" +
                "if tonumber(num) <= 0 then\n" +
                "    return 0;\n" +
                "else\n" +
                "    redis.call(\"decr\",qtKey);\n" +
                "    redis.call(\"sadd\",usersKey,userId);\n" +
                "end\n" +
                "\n" +
                "return 1;";
    }

}
